package com.shengqin.calculate.events.listeners;

import com.shengqin.calculate.data.CalculateSummaryModel;
import com.shengqin.calculate.data.UpdateParentResultModel;
import com.shengqin.calculate.events.CalculateSummaryEvent;
import com.shengqin.calculate.events.UpdateParentResultEvent;
import com.shengqin.entity.TestResult;
import com.shengqin.service.ISummaryResultService;
import com.shengqin.service.ITestResultService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.test.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UpdateParentResultListener {
    @Resource
    private ITestResultService testResultService;
    @Resource
    private ApplicationContext applicationContext;

    @SneakyThrows
    @EventListener(UpdateParentResultEvent.class)
    @Async
    public void onApplicationEvent(UpdateParentResultEvent event) {
        UpdateParentResultModel model = event.getModel();

        List<TestResult> newResultList = model.getTestResultList();
        Set<String> projectNames = new HashSet<>();

        if (CollectionUtils.isEmpty(newResultList)) {
            return;
        }

        newResultList.forEach(testResult -> {
            projectNames.add(testResult.getPrjName());
        });

        List<TestResult> parentTestResultList = testResultService.listByPlanIdAndPrjNamesAndStudyCode(model.getParentPlan().getId(), projectNames, model.getStudyCode());

        if (!CollectionUtils.isEmpty(parentTestResultList)) {
            List<Long> ids = parentTestResultList.stream().map(TestResult::getId).collect(Collectors.toList());
            testResultService.removeBatchByIds(ids);
//            log.info("删除父计划成绩成功 {} 条", ids.size());
        }

        newResultList.forEach(testResult -> {
            testResult.setPlanId(model.getParentPlan().getId());
            testResult.setId(null);
        });

        boolean saveNewResult = testResultService.saveOrUpdateBatch(newResultList);
        if (saveNewResult) {
//            log.info("更新新成绩至父计划成功 {} 条", newResultList.size());
            CalculateSummaryModel calculateSummaryModel = new CalculateSummaryModel();
            calculateSummaryModel.setStudyCode(model.getStudyCode());
            calculateSummaryModel.setPlan(model.getParentPlan());
            applicationContext.publishEvent(new CalculateSummaryEvent(this, calculateSummaryModel));
        }
    }
}